#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：图灵学习 
@File    ：4.协程中的回调函数.py
@IDE     ：PyCharm 
@Author  ：ChenLiGao
@Date    ：2024-12-04 16:39
'''
import asyncio

import aiohttp


# 回调函数: 任务完成后打印返回值结果
def download_completed_callback(task_obj):
    print("下载的内容为:", task_obj.result())


async def baidu_spider():
    print("---百度蜘蛛---")
    url = "https://www.baidu.com"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as r:
            return await r.text()


async def sogou_spider():
    print("---搜狗蜘蛛---")
    url = "https://www.sogou.com"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as r:
            return await r.text()


async def jingdong_spider():
    print("---京东蜘蛛---")
    url = "https://www.jd.com"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as r:
            return await r.text()

async def main():
    # 创建多个Task，且添加回调函数
    task_baidu = asyncio.create_task(baidu_spider())
    task_baidu.add_done_callback(download_completed_callback)

    task_sogou = asyncio.create_task(sogou_spider())
    task_sogou.add_done_callback(download_completed_callback)

    task_jingdong = asyncio.create_task(jingdong_spider())
    task_jingdong.add_done_callback(download_completed_callback)

    tasks = [task_baidu, task_sogou, task_jingdong]
    # 等待下载
    await asyncio.wait(tasks)

if __name__ == '__main__':
    asyncio.run(main())